package bb

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.bumptech.glide.Glide
import oa.lla.cca.R
import com.clean.scanlibrary.bean.CardInfoBean
import com.clean.scanlibrary.bean.DiscernTokenBean
import com.clean.scanlibrary.camera.utils.Base64Util
import com.clean.scanlibrary.camera.utils.FileUtil
import com.clean.scanlibrary.camera.utils.PicFileUtil
import com.clean.scanlibrary.dialog.CameraPremissDialog
import com.clean.scanlibrary.dialog.LoadingDialog
import com.clean.scanlibrary.http.DiscernViewMode
import com.clean.scanlibrary.http.HttpApi
import com.clean.scanlibrary.utils.SPreference
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import okhttp3.MediaType
import okhttp3.RequestBody
import java.net.URLEncoder

class CG : AppCompatActivity() {
    val REQ_CD_IMAGE = 101
    private var hasGetPermission by SPreference("ISHASCAMERAPERMISS", false)
    private val image = Intent(Intent.ACTION_GET_CONTENT)
    private var viewFromType = 0
    private var selectPath = ""
    private var discernTokenBean: DiscernTokenBean? = null
    private var viewMode: DiscernViewMode? = null
    private var loadingDialog: LoadingDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_scan)
        //0是港澳 1是台湾
        viewFromType = intent.getIntExtra("viewFromType", 0)
        viewMode = ViewModelProviders.of(this).get(DiscernViewMode::class.java)

        initView()
        initData()
    }

    private fun initData() {
        viewMode?.getDiscernToken(HttpApi.discernWordsAPIKey, HttpApi.discernWordsSecretKey)
        loadingDialog =
            LoadingDialog(this, R.style.dialog)
        loadingDialog?.show()

        //token请求返回
        viewMode?.getTokenLiveData?.observe(
            this
        ) { t ->
            loadingDialog?.dismiss()
            discernTokenBean = t
        }



        viewMode?.getCardInfoLiveData?.observe(this, object : Observer<CardInfoBean> {
            override fun onChanged(t: CardInfoBean) {
                if (t != null) {

                    if (TextUtils.isEmpty(t.CardNum.words)) {
                        return_card_info.text = "该通行证信息异常，请上传正确的通行证信息"
                        return_card_info.setTextColor(Color.RED)
                        return
                    }

                    val sb = StringBuilder()
                    sb.append("识别信息：\n")
                        .append("证件号码：" + t.CardNum.words + "\n")
                        .append("姓名：" + t.NameChn.words + "\n")
                        .append("姓名（英文）：" + t.NameEng.words + "\n")
                        .append("性别：" + t.Sex.words + "\n")

                    if (!TextUtils.isEmpty(t.Birthday.words)) {
                        sb.append("出生日期：" + t.Birthday.words + "\n")
                    } else {
                        sb.append("出生日期：\n")
                    }

                    if (!TextUtils.isEmpty(t.ValidDate.words)) {
                        sb.append("有效期限：" + t.ValidDate.words + "\n")
                    } else {
                        sb.append("有效期限：\n")
                    }

                    return_card_info.text = sb.toString()
                }
            }
        })
    }


    companion object {
        fun startCardScanActivity(context: Context, formType: Int) {
            val intent = Intent(context, CG::class.java)
            intent.putExtra("viewFromType", formType)
            context.startActivity(intent)
        }
    }


    private lateinit var card_scan_title: TextView
    private lateinit var to_get_pic: ImageView
    private lateinit var return_card_info: TextView
    private lateinit var start_scan: TextView

    private fun initView() {
        card_scan_title = findViewById(R.id.card_scan_title)
        to_get_pic = findViewById(R.id.to_get_pic)
        return_card_info = findViewById(R.id.return_card_info)
        start_scan = findViewById(R.id.start_scan)

        if (viewFromType == 0) {
            card_scan_title.text = "港澳通行证识别"
        } else {
            card_scan_title.text = "台湾通行证识别"
        }
        to_get_pic.setOnClickListener {
            if (hasGetPermission) {
                togetPic()
                return@setOnClickListener
            }

            val permissDialog = CameraPremissDialog(this, R.style.dialog)
            permissDialog.show()
            permissDialog.setOnDialogClickListener(object : CameraPremissDialog.OnDialogClickListener {
                override fun onAgree() {
                    toPremiss()
                }

                override fun onCancel() {
                    Toast.makeText(this@CG, "没有相机授权与本地存储权限授权，无法使用！", Toast.LENGTH_SHORT).show()
                    finish()
                }
            })


        }


        start_scan.setOnClickListener {
            toUploadPic()
        }


    }


    private fun toPremiss() {
        XXPermissions.with(this) // 不适配 Android 11 可以这样写
            //.permission(Permission.Group.STORAGE)
            // 适配 Android 11 需要这样写，这里无需再写 Permission.Group.STORAGE
            .permission(CD.REQUIRED_PERMISSIONS)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, all: Boolean) {
                    if (all) {
                        hasGetPermission = true
                        togetPic()
                    }
                }

                override fun onDenied(permissions: List<String>, never: Boolean) {
                    if (never) {
                        Toast.makeText(this@CG, "被永久拒绝授权，请手动授予存储权限！", Toast.LENGTH_SHORT).show()
                        XXPermissions.startPermissionActivity(this@CG, permissions)
                    } else {
                        Toast.makeText(this@CG, "没有相机授权与本地存储权限授权，无法使用！", Toast.LENGTH_SHORT).show()
                    }

                    finish()
                }
            })
    }


    private fun togetPic() {
        image.setType("image/*")
        image.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        startActivityForResult(image, REQ_CD_IMAGE)
    }


//    // 权限申请
//    private fun allPermissionsGranted() = CD.REQUIRED_PERMISSIONS.all {
//        ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
//    }


//    // 权限申请结果
//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (requestCode == CD.REQUEST_CODE_PERMISSIONS) {
//            hasGetPermission = true
//            if (allPermissionsGranted()) {
//                togetPic()
//            } else {
//                Toast.makeText(this, "没有相机授权与本地存储权限授权，无法使用！", Toast.LENGTH_SHORT).show()
//                finish()
//            }
//        }
//    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, _data: Intent?) {
        super.onActivityResult(requestCode, resultCode, _data)

        if (requestCode == REQ_CD_IMAGE && resultCode == RESULT_OK) {
            if (_data != null) {

                val _filePath = ArrayList<String>()
                if (_data != null) {
                    if (_data.clipData != null) {
                        for (_index in 0 until _data.clipData!!.itemCount) {
                            val _item = _data.clipData!!.getItemAt(_index)
                            _filePath.add(
                                PicFileUtil.convertUriToFilePath(
                                    applicationContext,
                                    _item.uri
                                )
                            )
                        }
                    } else {
                        _filePath.add(
                            PicFileUtil.convertUriToFilePath(
                                applicationContext,
                                _data.data
                            )
                        )
                    }
                }
                selectPath = _filePath.get(0)
                Glide.with(this).load(_data.data).into(to_get_pic)
            }
        }
    }


    fun toUploadPic() {
        if (TextUtils.isEmpty(selectPath)) {
            Toast.makeText(this, "请先上传图片", Toast.LENGTH_SHORT).show()
            return
        }
        Toast.makeText(this, "正在识别请稍后", Toast.LENGTH_SHORT).show()

        var exitentrypermit_type = "hk_mc_passport_front"

        exitentrypermit_type = if (viewFromType == 0) {
            "hk_mc_passport_front"
        } else {
            "tw_passport_front"
        }

        val compressQuality: String = FileUtil.compressQuality(this, selectPath)
        val imgData: ByteArray = FileUtil.readFileByBytes(compressQuality)
        val imgStr: String = Base64Util.encode(imgData)
        val imgParam: String = URLEncoder.encode(imgStr, "UTF-8")
        val mediaType = MediaType.parse("application/x-www-form-urlencoded")
        val body = RequestBody.create(mediaType, "image=${imgParam}&exitentrypermit_type=" + exitentrypermit_type)
        viewMode?.getDiscernCardPic(HttpApi.gangao_iccard_url + "?access_token=" + discernTokenBean?.access_token, body)

    }


}